package com.speechb.controller;

import com.speechb.bean.ConstantParas;
import com.speechb.bean.UserBean;
import com.speechb.common.codec.Md5Utils;
import com.speechb.common.text.CheckUtils;
import com.speechb.common.text.IpUtil;
import com.speechb.common.text.WebUtil;
import com.speechb.controller.base.BaseController;
import com.speechb.entity.LoginHistory;
import com.speechb.entity.User;
import com.speechb.manager.ThreadPoolManager;
import com.speechb.mapper.dao.LoginHistoryDao;
import com.speechb.mapper.dao.UserDao;
import com.speechb.modules.system.web.annotation.CheckParam;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * @author : llj
 * @version :2.1.0
 * @date : 2020/7/5 14:13
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Autowired
    UserDao<User> userDao;
    @Autowired
    LoginHistoryDao<LoginHistory> loginHistoryDao;

    @ResponseBody
    @PostMapping("/login-check")
    @CheckParam({"username", "password"})
    public void login() {
        String username = getPara("username");
        String password = getPara("password");
        User user = userDao.findByUsername(username);
        if (user != null) {
            // 加密
             password =  Md5Utils.md5(password + username,3);
            // 对比密码
            if (StringUtils.equals(user.getPassword(), password)) {
                //用户登录成功更换SessionId
                user.setUsername(username);
                // 获取用户基本信息
                UserBean userBean = new UserBean();
                userBean.setId(user.getId());
                userBean.setUsername(username);
                userBean.setNickname(user.getNickname());
                userBean.setAvatarUrl(user.getAvatar_url());
                addUserBean(userBean);
                setData(user);
                saveLoginInfo("账号密码登录，web_useragent："+ WebUtil.getUserAgent(getRequest()), username, user.getId(), ConstantParas.STATUS_LOGIN_SUCCESS);
                renderUnCompressSuccess();
            } else {//密码错误
                saveLoginInfo("密码错误，web_useragent："+ WebUtil.getUserAgent(getRequest()), username, "", ConstantParas.STATUS_LOGIN_FIAL);
                renderPasswordNoMatch();
            }
        } else {
            // 用户不存在
            renderUserNoExist();
        }
    }
    
    @PostMapping("/register")
    @ResponseBody
    public void register() {
        String code = getPara("captcha");
        String type = getPara("type");
//        if (!ImageController.checkCode(code, type)) {
//            LOGGER.warn("[register]Activation code mismatch");
//            renderFail("验证码输入有误！");
//            return;
//        }
        String password = getPara("password");
        if (!CheckUtils.checkPassword(password)) {
            renderFail("密码格式有误，需要由字母和数字组合！");
            LOGGER.warn("[register]Incorrect format of verification code");
            return;
        }
        String username = getPara("username");
        if (!CheckUtils.checkUserName(username)) {
            renderFail("用户名只能由数字和字母组合,最小长度为4");
            LOGGER.warn("[register]Incorrect format of verification code");
            return;
        }

        User user = userDao.findByUsername(username);
        // 判断用户名是否唯一
        if (user != null) {
            renderUserExist();
            return;
        }
        user = new User();
        user.setPassword(password);
        user.setUsername(username);
        userDao.insert(user);
        UserBean userBean = new UserBean();
        userBean.setId(user.getId());
        userBean.setUsername(username);
        userBean.setVip(false);
        addUserBean(userBean);
        setData(userBean);
        saveLoginInfo("用户注册成功，"+ WebUtil.getUserAgent(getRequest()), username, user.getId(), ConstantParas.REGISTER_SUCCESS);
        renderUnCompressSuccess();
    }

    @GetMapping("/login-status")
    @ResponseBody
    public void userInfo() {
        String id = UserBean.getId();
        if (StringUtils.isEmpty(id)) {
            // 失败代表未登录
            renderFail();
            return;
        }
        User userBean = new User();
        userBean.setId(UserBean.getId());
        userBean.setUsername(UserBean.getUsername());
        userBean.setNickname(UserBean.getNickname());
        userBean.setVip(UserBean.isVIP());//userVipService.isVip(id)
        userBean.setAvatar_url(UserBean.getAvatarUrl());
        setData(userBean);
        renderUnCompressSuccess();
    }
    /**
     * 保存用户登录信息
     * status_id
     * 14登录成功
     * 15 登录失败
     */
    public void saveLoginInfo(final String remark, final String username, final String uid, final int statusId) {
        final String phoneModel = getPara("phone_model");
        final String phoneBrand = getPara("phone_brand");
        final String platform = getPara("platform");
        final String ip = IpUtil.getIpAddr(getRequest());
        final String phoneSign = getPara("phone_sign");
        ThreadPoolManager.newInstance().addExecuteTask(() -> {
            LoginHistory history = new LoginHistory();
            history.setIp(ip);
            history.setPhone_model(phoneModel);
            history.setPhone_brand(phoneBrand);
            history.setPlatform(platform);
            history.setRemark(remark);
            history.setUid(uid);
            history.setStatus(statusId);
            history.setPhone_sign(phoneSign);
            history.setUsername(username);
            try {
                loginHistoryDao.insert(history);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }


    @RequestMapping("/logout")
    @ResponseBody
    public void logout(HttpSession session) {
        renderSuccess();
        session.invalidate();
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
    }
}
